<template>
  <div class="chart-container">
    <div class="chart-header">
      <h3>{{ chartTitle }}</h3> 
    </div>
  </div>
  
<div class="chart-container">
  	<!-- 图表按钮 -->
  	<div class="chart-controls">
  	  <button @click="toggleChartType">
  	    {{ chartType === 'line' ? '切换到柱状图' : '切换到折线图' }}
  	  </button>
  	  <button @click="addRandomData">添加数据</button>
  	  <button @click="resetData">重置数据</button>
  	</div>
</div>

<div class="chart-container">
  	<!-- 图表主体 -->
  	<div ref="chartRef" class="chart" style="width: 100%; height: 400px;"></div>
</div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick, computed } from 'vue'; 
// 新增 computed 导入
import * as echarts from 'echarts';

const chartRef = ref(null);
const chartInstance = ref(null);

// 图表配置
const chartTitle = ref('数据趋势分析');
const chartType = ref('line');

// 图表数据
const currentData = ref([
  { date: '2023-01-01', value: 120 },
  { date: '2023-01-02', value: 132 },
  { date: '2023-01-03', value: 101 },
  { date: '2023-01-04', value: 134 },
  { date: '2023-01-05', value: 90 },
  { date: '2023-01-06', value: 230 },
  { date: '2023-01-07', value: 210 }
]);


// 初始化图表
const initChart = () => {
  chartInstance.value = echarts.init(chartRef.value);
  
  const option = {
    title: {
      text: chartTitle.value,
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        const param = params[0];
        return `日期: ${param.name}<br/>数值: ${param.value}`;
      }
    },
    xAxis: {
      type: 'category',
      data: currentData.value.map(item => item.date)
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: currentData.value.map(item => item.value),
      type: chartType.value,
      smooth: true,
      itemStyle: {
        color: '#36a2eb'
      },
      lineStyle: {
        color: '#36a2eb'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0, y: 0, x2: 0, y2: 1,
          colorStops: [{
            offset: 0, color: 'rgba(54, 162, 235, 0.4)' // 0% 处的颜色
          }, {
            offset: 1, color: 'rgba(54, 162, 235, 0)' // 100% 处的颜色
          }]
        }
      }
    }]
  };
  chartInstance.value.setOption(option);
};

// 更新图表
const updateChart = () => {
  if (!chartInstance.value) return;
  const option = {
    xAxis: {
      data: currentData.value.map(item => item.date)
    },
    series: [{
      data: currentData.value.map(item => item.value),
      type: chartType.value
    }]
  }; 
  chartInstance.value.setOption(option);
};

// 切换图表类型
const toggleChartType = () => {
  chartType.value = chartType.value === 'line' ? 'bar' : 'line';
  updateChart();
};

// 添加随机数据
const addRandomData = () => {
  const lastDate = currentData.value[currentData.value.length - 1]?.date || '2023-01-01';
  const nextDate = new Date(lastDate);
  nextDate.setDate(nextDate.getDate() + 1);
  const formattedDate = nextDate.toISOString().split('T')[0];
  
  currentData.value.push({
    date: formattedDate,
    value: Math.floor(Math.random() * 200) + 50
  });
  
  // 限制数据点数量，保持图表可读性
  if (currentData.value.length > 15) {
    currentData.value.shift();
  }
  
  updateChart();
};

// 重置数据
const resetData = () => {
  currentData.value = [
    { date: '2023-01-01', value: 0 },
    { date: '2023-01-02', value: 132 },
    { date: '2023-01-03', value: 10 },
    { date: '2023-01-04', value: -134 },
    { date: '2023-01-05', value: -90 },
    { date: '2023-01-06', value: -230 },
    { date: '2023-01-07', value: 210 }
  ];
  updateChart();
};

// 监听窗口大小变化，调整图表
const handleResize = () => {
  if (chartInstance.value) {
    chartInstance.value.resize();
  }
};

// 生命周期钩子
onMounted(() => {
  initChart();
  window.addEventListener('resize', handleResize);
});

// 监听数据变化，更新图表
watch(currentData, () => {
  updateChart();
});

// 监听图表类型变化，更新图表
watch(chartType, () => {
  updateChart();
});

// 组件卸载时清理
onUnmounted(() => {
  if (chartInstance.value) {
    chartInstance.value.dispose();
    chartInstance.value = null;
  }
  window.removeEventListener('resize', handleResize);
});
</script>

<style scoped>
.chart-container {
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chart-controls {
  display: flex;
  gap: 10px;
}

.chart-controls button {
  background-color: #4CAF50;
  border: none;
  color: white;
  padding: 8px 16px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 14px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.chart-controls button:hover {
  background-color: #45a049;
}

.chart-info {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #eee;
}

.chart-info p {
  margin: 0;
  padding: 0 10px;
  border-right: 1px solid #eee;
}

.chart-info p:last-child {
  border-right: none;
}
</style>
    